package lt.marsrutai.mobile.android.map;

import java.util.ArrayList;
import java.util.List;

import lt.marsrutai.mobile.android.AppContext;
import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.StopMapActivity;
import lt.marsrutai.mobile.android.activity.intent.StopMapIntentHolder;
import lt.marsrutai.mobile.android.exception.DataAccessException;
import lt.marsrutai.mobile.android.model.Stop;
import android.app.ProgressDialog;
import android.os.AsyncTask;

public class GetStopsAsyncTask extends AsyncTask<StopMapIntentHolder, Integer, List<Stop>> {
    private StopMapActivity activity;
    private ProgressDialog progressDialog;
    
    public GetStopsAsyncTask(StopMapActivity activity) {
        this.activity = activity;
        progressDialog = new ProgressDialog(activity);        
    }
    
    @Override
    protected void onPreExecute() {
        progressDialog.setMessage(activity.getString(R.string.loading_stops));
        progressDialog.show();
    }
    
    @Override
    protected List<Stop> doInBackground(StopMapIntentHolder... params) {        
        List<Stop> aggregatedStops = new ArrayList<Stop>();
        for (StopMapIntentHolder intentHolder : params) {
            aggregatedStops.addAll(getStops(intentHolder));
        }
        
        return aggregatedStops;
    }
    
    @Override
    protected void onPostExecute(List<Stop> result) {
        activity.runOnUiThread(activity.getAsyncTaskResultProcessor());
        progressDialog.dismiss();
    }
    
    private List<Stop> getStops(StopMapIntentHolder intentHolder) {
        String scopeFolder = intentHolder.getScopeFolder();
        String trackId = intentHolder.getTrackId();
        String stopId = intentHolder.getStopId();
        
        List<Stop> stops = new ArrayList<Stop>();
        
        try {
            if (null == trackId) {
                stops.add(AppContext.getDataService().getStopById(scopeFolder, stopId));
            }
            else {
                stops = AppContext.getDataService().getTrackStops(scopeFolder, trackId);
            }
        }
        catch (DataAccessException e) {
            e.printStackTrace();
        }
        
        return stops;
    }
}
